'use strict';

/**
 * @name: ZhouGe
 * @msg: 更新版本提示弹窗
 * @param {curV} 当前最新版
 * @param {reqV} 前一版本
 * @return {*} 当前版本大于前一版本号，返回true
 */
function compare(curV, reqV) {
  if (curV && reqV) {
    //将两个版本号拆成数字
    var arr1 = curV.split('.'),
      arr2 = reqV.split('.');
    var minLength = Math.min(arr1.length, arr2.length),
      position = 0,
      diff = 0;
    while (
      position < minLength &&
      (diff = parseInt(arr1[position]) - parseInt(arr2[position])) == 0
    ) {
      position++;
    }
    diff = diff != 0 ? diff : arr1.length - arr2.length;
    return diff > 0;
  } else {
    //输入无版本号返回false，需更新
    return false;
  }
}

class UpdateToYourweb {
  constructor(options) {
    if (!options) {
      throw new Error('options 参数不能为空！');
    }
    if (options.length < 1) {
      throw new Error('options 参数列表为空');
    }
    if (!options.filename) {
      throw new Error('options.filename 版本存储json文件不存在！');
    }
    this.options = options;
    this.initVerion();
    setInterval(
      function () {
        this.initVerion();
      }.bind(this),
      this.options.looptime ? this.options.looptime : 10000
    );
  }

  /**
   * @msg: 获取json数据判断是否有更新
   */
  initVerion() {
    var xmlhttp;
    if (window.XMLHttpRequest) {
      // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp = new XMLHttpRequest();
    } else {
      // code for IE6, IE5
      // eslint-disable-next-line no-undef
      xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
    }
    xmlhttp.onreadystatechange = function () {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        if (!localStorage.getItem('versionCode')) {
          localStorage.setItem('versionCode', xmlhttp.responseText);
          return;
        }
        if (
          localStorage.getItem('versionCode') &&
          compare(
            JSON.parse(xmlhttp.responseText).versionCode,
            JSON.parse(localStorage.getItem('versionCode')).versionCode
          )
        ) {
          if (this.options.text) {
            alert(this.options.text);
          }
          localStorage.setItem('versionCode', xmlhttp.responseText);
          location.reload(true);
        }
      }
    }.bind(this);
    xmlhttp.open(
      'GET',
      this.options.filename + '?v=' + new Date().getTime(),
      true
    );
    xmlhttp.send();
  }
}

export default UpdateToYourweb;
